package org.komarichin.jdo.dao;

import org.apache.commons.collections.CollectionUtils;
import org.komarichin.beans.dao.ILanguageDAO;
import org.komarichin.jdo.persistence.Language;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;

/**
 * User: Mykhaylo Komarichyn
 * Date: 03.02.2010
 * Time: 14:24:17
 */
@Transactional(readOnly = true)
public class LanguageDAO extends JdoGenericDAOSupport<Language, Long> implements ILanguageDAO<Language, Long> {

    private static final Logger log = LoggerFactory.getLogger(LanguageDAO.class);
    private static final long serialVersionUID = -3094762594763824551L;

    public LanguageDAO(Class<Language> type) {
        super(type);
    }


    @Override
    @Transactional(readOnly = false)
    public Long saveOrUpdate(Language lang) {
        log.info("save Or Update entity: {}", lang);
        Language l = getJdoTemplate().getObjectById(getType(), lang.getId());
        if (l == null) {
            return save(l).getId();
        } else {
            l.setIsoName(lang.getIsoName());
            return l.getId();
        }
    }


    @Override
    public Language findByName(String name) {
        log.debug("find by name: {}", name);
        Collection result = getJdoTemplate().find(Language.class, "isoName == pIsoName", "String pIsoName", name);
        log.debug("result size: {}", result.size());
        return result.size() > 0 ? (Language) CollectionUtils.get(result, 0) : null;
    }


    @Override
    public Language newInstance() {
        return new Language();
    }
}
